<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'wh:ll:whTmLlH:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="95%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <!-- <template #rdsSelect>
        
      </template> -->

      <template #whTmLlRdsList>
        <BasicTable @register="registerWhTmLlRdsTable" @row-click="handleWhTmLlRdsRowClick" />
        <a-button class="mt-2" @click="handleWhTmLlRdsAdd" v-auth="'wh:ll:whTmLlH:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
    <ListSelect
      ref="listSelectRef"
      v-model:value="itemCodes"
      :labelValue="itemNames"
      :selectType="selectType"
      :checkbox="true"
      :params="queryParams"
      :selectList="selectListRef"
      @select="handSelect"
      v-show="false"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsWhLlWhTmLlHForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { WhTmLlH, whTmLlHSave, whTmLlHForm } from '/@/api/wh/ll/whTmLlH';
  import { ListSelect } from '/@/components/ListSelect';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('wh.ll.whTmLlH');
  const { showMessage } = useMessage();
  const record = ref<WhTmLlH>({} as WhTmLlH);
  const itemCodes = ref('');
  const itemNames = ref('');
  const queryParams = ref({});
  const selectType = ref('whMasterSelect');
  const listSelectRef = ref<any>(null);
  const selectListRef = ref<any>([]);

  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增领料任务') : t('编辑领料任务'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('发料仓库'),
      field: 'cwhcode',
      component: 'Input',
      componentProps: {
        dictType: 'ASD_WH',
      },
      // required: true,
      show: false,
    },
    {
      label: t('需求仓库'),
      field: 'xqcwhcode',
      component: 'Input',
      componentProps: {
        dictType: 'ASD_WH',
      },
      // required: true,
      show: false,
    },
    {
      label: t('总成'),
      field: 'cinvcode',
      fieldLabel: 'basInv.cinvaddcode',
      component: 'ListSelect',
      componentProps: {
        selectType: 'cinvaddcodeSelect',
      },
    },
    {
      label: t('数量'),
      field: 'iqty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('需求时间'),
      field: 'xqDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
      },
    },
    {
      label: t('选择'),
      field: 'selIds',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rdsSelect',
      show: false,
    },
    {
      label: t('类型'),
      field: 'area',
      component: 'Input',
      required: true,
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('领料明细'),
      field: 'whTmLlRdsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'whTmLlRdsList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerWhTmLlRdsTable, whTmLlRdsTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleWhTmLlRdsDelete.bind(this, record),
          },
          auth: 'wh:ll:whTmLlH:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setWhTmLlRdsTableData(_res: Recordable) {
    whTmLlRdsTable.setColumns([
      {
        title: t('Master编码'),
        dataIndex: 'bomcode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('存货编码'),
        dataIndex: 'cinvcode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('存货代码'),
        dataIndex: 'cinvaddcode',
        key: 'cinvaddcode',
        width: 170,
      },
      {
        title: t('存货编码'),
        dataIndex: 'basInv.cinvcode',
        key: 'basInv.cinvcode',
        width: 170,
      },
      {
        title: t('存货名称'),
        dataIndex: 'basInv.cinvname',
        key: 'basInv.cinvname',
        width: 170,
      },
      {
        title: t('构成比例'),
        dataIndex: 'frate',
        width: 60,
        align: 'right',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
        },
        editRule: false,
      },
      {
        title: t('需求数'),
        dataIndex: 'iqty',
        width: 80,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 16,
          rules: [
            {
              pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/,
              message: t('请输入一个数值'),
            },
          ],
        },
        editRule: true,
      },
    ]);
    whTmLlRdsTable.setTableData(record.value.whTmLlRdsList || []);
  }

  function handleWhTmLlRdsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleWhTmLlRdsAdd() {
    const data = getFieldsValue();
    if(whTmLlRdsTable.getDataSource().length > 0){
      whTmLlRdsTable.getDataSource().forEach((item) => {
        selectListRef.value.push({
          id: item.id,
          cinvcode: item.basInv.cinvcode,
          iqty: item.iqty,
          basInv: {
            cinvname: item.basInv.cinvname,
          },
        });
      });
    }else{
      selectListRef.value = [];
    }
    queryParams.value = {
      cinvCode: data.cinvcode,
      iqty: data.iqty,
      'basInv.cinvaddcode': data.basInv.cinvaddcode,
      'basInv.cinvaddcodebasInv.cinvname': data.basInv.cinvname,
    };
    console.log('queryParams', queryParams.value, data);
    if (!queryParams.value.cinvcode) {
      setTimeout(() => {
        console.log('请选择存货编码', listSelectRef.value);
        listSelectRef.value.openSelectModal();
      });
    }
  }

  /**
   * 选择
   * @param selectData
   */
  function handSelect(selectData) {
    console.log(selectData, 'selectData');
    if (selectType.value === 'whMasterSelect') {
      if (whTmLlRdsTable.getDataSource().length > 0) {
        // 数组selectData 过滤掉basInv.cinvcode 相同的
        // console.log(whTmLlRdsTable.getDataSource());
        const newDataSource = [...whTmLlRdsTable.getDataSource(), ...selectData];
        newDataSource.forEach((item) => {
          item.id = '';
          item.isNewRecord = true;
          item.editable = true;
          item.bomcode = queryParams.value.cinvCode;
          item.cinvcode = item.basInv.cinvcode;
          item.cinvaddcode = item.basInv.cinvaddcode;
          item.frate = item.unitNumber;
          item.iqty = item.iqty;
          item.area = '';
          item.xqDate = '';
        });
        const seen = new Map();
        const uniqueDataSource = newDataSource.filter(item => {
          if (seen.has(item.cinvcode)) {
            return false; // 如果已经见过这个 cinvcode，则过滤掉该元素
          } else {
            seen.set(item.cinvcode, true); // 否则，记录这个 cinvcode 并保留该元素
            return true;
          }
        });
        whTmLlRdsTable.setTableData(uniqueDataSource);

        // whTmLlRdsTable.getDataSource().forEach((record) => {
        //   selectData.forEach((item) => {
        //     if (record.cinvcode == item.cinvCode) return;
        //     whTmLlRdsTable.insertTableDataRecord({
        //       id: '',
        //       ...item,
        //       isNewRecord: true,
        //       editable: true,
        //       bomcode: queryParams.value.cinvCode,
        //       cinvcode: item.basInv.cinvcode,
        //       frate: item.unitNumber,
        //       iqty: item.iqty,
        //       area: '',
        //       xqDate: '',
        //     });
        //   });
        // });
      } else {
        selectData.forEach((item) => {
          whTmLlRdsTable.insertTableDataRecord({
            id: '',
            ...item,
            isNewRecord: true,
            editable: true,
            bomcode: queryParams.value.cinvCode,
            cinvcode: item.basInv.cinvcode,
            cinvaddcode: item.basInv.cinvaddcode,
            frate: item.unitNumber,
            iqty: item.iqty,
            area: '',
            xqDate: '',
          });
        });
      }
    } else {
      whTmLlRdsTable.insertTableDataRecord({
        id: new Date().getTime(),
        isNewRecord: true,
        editable: true,
      });
    }
  }

  function handleWhTmLlRdsDelete(record: Recordable) {
    whTmLlRdsTable.deleteTableDataRecord(record);
  }

  async function getWhTmLlRdsList() {
    let whTmLlRdsListValid = true;
    let whTmLlRdsList: Recordable[] = [];
    for (const record of whTmLlRdsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        whTmLlRdsListValid = false;
      }
      whTmLlRdsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
        area: record.editValueRefs.area,
        xqDate: record.editValueRefs.xqDate,
      });
    }
    for (const record of whTmLlRdsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      whTmLlRdsList.push({
        ...record,
        status: '1',
      });
    }
    if (!whTmLlRdsListValid) {
      throw { errorFields: [{ name: ['whTmLlRdsList'] }] };
    }
    return whTmLlRdsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await whTmLlHForm(data);
    record.value = (res.whTmLlH || {}) as WhTmLlH;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setWhTmLlRdsTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      data.whTmLlRdsList = await getWhTmLlRdsList();
      // console.log('submit', params, data, record);
      const res = await whTmLlHSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
